'use strict';

const common = require('../lib/common');
const moment = require('moment');
const qrcodeDb = require('../models/qrcode');
const log =  require('../lib/log4js')();

/* 获取二维码的信息代码 */
async function setCode(req, res){
  
  try{

    var params = JSON.parse(req.body);

    if (typeof(params.invalidTime) != 'Number'){
      params.invalidTime = 1;
    };

    var code = common.getQrcode({openId: params.openId}); //获取二维码代码
    var invalidTimestamp = moment().add(params.invalidTime, 'hours').format('X');  //设置1小时过期

    var ret = await qrcodeDb.create({
      orderNo: params.orderNo,
      code: code,
      openId: params.openId,
      type: 1, 
      lon: params.lon,
      lat: params.lat,
      status: 1,
      invalidTimestamp: invalidTimestamp,
      accode: params.accode,
      createTime: moment().format('YYYY-MM-DD HH:mm:ss')
    });

    res.send({
      error: null,
      code: code
    });

  }catch(error){
    log.error('api res:' + req.route.path + ' res error: ' + error.toString());
    res.send({error: error});
  };

};

async function checkCode(req, res){

  try{

    var params = req.query;

    var data = await qrcodeDb.findOne({where: {code: params.code}});

    if (data != null){
      
      if (data.status == 0){
        res.send({error: 'data is invalidTimestamp'});
      }else if (data.invalidTimestamp < parsenInt(moment().format('X'))){
        let ret = await qrcodeDb.update({status: 0}, {where: {id: data.id}});
        res.send({error: 'data is invalidTimestamp'});
      }else{
        res.send({
          error: null,
          openId: data.openId,
          lon: data.lon,
          lat: data.lat
        });
      };

    }else{
      res.send({error: 'data is null'});
    };

  }catch(error){
    log.error('api:' + req.route.path + ' res error: ' + error.toString());
    res.send({error: error});
  };

};

module.exports = {
  setCode: setCode,
  checkCode: checkCode
};